<!--
 * @Date: 2024-04-21 15:27:20
 * @Author: LiSong
 * @LastEditors: LiSong
 * @LastEditTime: 2024-08-13 20:40:20
 * @Description: PDF预览器
-->
<template>
  <div class="pdf-container" id="pdfContariner">
    <div></div>
  </div>
</template>

<script setup>
import { nextTick, ref, watch } from 'vue';

const props = defineProps({
  pdf: { type: String },
  showDownload: { type: Boolean, default: false }
})
const env = import.meta.env
const pdfUrl = '/pdfjs-dist/web/viewer.html?file='
// 版本 4.1.392 ---> 3.11.174
const defaultPath = env.PROD ? `${env.VITE_PUBLIC_PATH}${pdfUrl}` : pdfUrl

// 加载
const loadFile = (url) => {
  let iframe = document.createElement('iframe')
  iframe.width = '100%'
  iframe.height = '100%'
  iframe.classList = ['pdf-iframe']
  iframe.src = defaultPath + encodeURIComponent(url)
  const container = document.getElementById("pdfContariner");
  container.replaceChild(iframe, container.firstChild);
  nextTick(() => {
    closeIframeLoading(iframe)
  }) 
}

// 关闭 iframe loading
const closeIframeLoading = (iframe) => {
	nextTick(() => {
		if (!iframe) return false;
    iframe.onload = () => {
      // 处理报表中表格样式问题
      setTimeout(() => {
        const itemDocument = iframe.contentDocument
        const style = itemDocument.createElement("style");
        style.type = 'text/css'
        style.innerHTML = `
          #download, #print, #openFile,
          #editorModeSeparator,
          #editorModeButtons,
          #secondaryOpenFile {
            display: none;
          }
        `;
        itemDocument.head.appendChild(style);
      }, 150)
    };
	});
};

watch(
  () => props.pdf,
  (newValue, oldValue) => {
    if (newValue) {
      loadFile(newValue)
    }
  }
)

</script>

<style lang="scss" scoped>
.pdf-container {
  width: 100%;
  height: 100%;
}
:deep(.pdf-iframe) {
  width: 100%;
  height: 100%;
  border: none;
}
</style>